package com.pjchat.pjchatclient.receiver;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.net.SocketException;

import javax.swing.JOptionPane;

import com.ita.im.model.Unit;
import com.pjchat.pjchatclient.frame.MyLoginFrame;
import com.pjchat.pjchatclient.handler.BasicHandler;
import com.pjchat.pjchatclient.handlerfactory.HandlerFactory;
import com.pjchat.pjchatclient.util.JsonUtil;

public class LoginReceiverRunnable implements Runnable {
	private MyLoginFrame myFrame;
	private BasicHandler handler;
	private BufferedReader br;
	private BufferedWriter bw;

	public LoginReceiverRunnable(MyLoginFrame myFrame, BufferedReader br,
			BufferedWriter bw) throws IOException {
		this.myFrame = myFrame;
		this.br = br;
		this.bw = bw;
	}

	@Override
	public void run() {
		while (true) {
			Unit unit = null;
			try {
				try {
					unit = JsonUtil.jsonObjectToUnit(br.readLine());
				} catch (SocketException e) {
					JOptionPane.showMessageDialog(null, "Socket close");
					System.exit(0);
				}
			} catch (IOException e) {
				e.printStackTrace();
				break;
			}
			if (unit != null) {
				handler = HandlerFactory.produce(unit.getType());
				Unit result = handler.doResponse(myFrame, unit, br, bw);
				if (result != null) {
					break;
				}
			}
		}

	}
}
